﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing;
using System.IO;
using TDT.Land.Utilities;


namespace TDT.Land.Web.Controllers
{
    public class BaseController : Controller
    {
        #region Thông Tin User

        public string UserName
        {
            get
            {
                if (Session["_UserName"] != null && Session["_UserName"] is string)
                {
                    return Session["_UserName"].ToString();
                }

                return string.Empty;
            }
            set
            {
                Session["_UserName"] = value;
            }
        }

        public Guid UserID
        {
            get
            {
                if (Session["_UserID"] != null && Session["_UserID"] is Guid)
                {
                    return (Guid)Session["_UserID"];
                }

                return Guid.Empty;
            }
            set
            {
                Session["_UserID"] = value;
            }
        }

        public string UserNameFull
        {
            get
            {
                if (Session["_UserNameFull"] != null && Session["_UserNameFull"] is string)
                {
                    return Session["_UserNameFull"].ToString();
                }

                return string.Empty;
            }
            set
            {
                Session["_UserNameFull"] = value;
            }
        }

        public string UserTypeSess
        {
            get
            {
                if (Session["_UserType"] != null && Session["_UserType"] is string)
                {
                    return Session["_UserType"].ToString();
                }
                return string.Empty;
            }
            set
            {
                Session["_UserType"] = value;
            }
        }

        public int UserPermission
        {
            set
            {
                Session["_UserPermission"] = value;
            }

            get
            {
                return Session["_UserPermission"] == null ? 0 : int.Parse(Session["_UserPermission"].ToString());
            }

        }


        #endregion

        public string ImagePath
        {
            get
            {
                return "Uploads/";
            }
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UploadImage(HttpPostedFileBase upload, string CKEditorFuncNum, string CKEditor, string langCode)
        {
            string url; // url to return
            string message; // message to display (optional)


            // will create http://localhost:1457/Content/Images/my_uploaded_image.jpg
            

            //luu stream vào file trong thu muc uploads
        //    ResizeImage(upload.InputStream, ImagePath + Guid.NewGuid() + ".jpg", 100, 100, true);
           // Request.Files[0].SaveAs("C:\\test.jpg");
           var path = test();

           url = Request.Url.GetLeftPart(UriPartial.Authority) + "/" + path;

           // passing message success/failure
           message = "Image was saved correctly";

            // since it is an ajax request it requires this string
            string output = @"<html><body><script>window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", \"" + url + "\", \"" + message + "\");</script></body></html>";
            return Content(output);
        }

        public string test() {
            string filePath = "/Upload";
            string fileName = Guid.NewGuid().ToString();
            var filePosted = Request.Files[0];
            if (filePosted != null && filePosted.ContentLength > 0)
            {
                string fileNameApplication = System.IO.Path.GetFileName(filePosted.FileName);
                string fileExtensionApplication = System.IO.Path.GetExtension(fileNameApplication);

                // generating a random guid for a new file at server for the uploaded file
                string newFile = fileName + fileExtensionApplication;
                // getting a valid server path to save
                filePath = System.IO.Path.Combine(Server.MapPath("../Uploads"), newFile);

                if (fileNameApplication != String.Empty)
                {
                    filePosted.SaveAs(filePath);
                }
                filePath = "Uploads/" + newFile;
            }
            return filePath;
        }

        public int ResizeImage(Stream OriginalFile, string NewFile, int NewWidth, int MaxHeight, bool OnlyResizeIfWider)
        {
            System.Drawing.Image FullsizeImage = System.Drawing.Image.FromStream(OriginalFile);

            // Prevent using images internal thumbnail
            FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
            FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

            if (OnlyResizeIfWider)
            {
                if (FullsizeImage.Width <= NewWidth)
                {
                    NewWidth = FullsizeImage.Width;
                }
            }

            int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;
            if (NewHeight > MaxHeight)
            {
                // Resize with height instead
                NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;
                NewHeight = MaxHeight;
            }

            System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);

            // Clear handle to original file so that we can overwrite it if necessary
            FullsizeImage.Dispose();

            NewImage.Save(NewFile);
            return NewHeight;
        }


        #region Phân Quyền
        public class CustomAuthorizeAttribute : AuthorizeAttribute
        {
            protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
            {
                if (!string.IsNullOrEmpty(Roles))
                {
                    if (httpContext != null)
                    {
                        string _permission = httpContext.Session["_UserPermission"] != null ? httpContext.Session["_UserPermission"].ToString() : string.Empty;
                        int _UserPermission = !string.IsNullOrEmpty(_permission) ? int.Parse(_permission) : 0;

                        int RolesNum = 0;
                        int.TryParse(Roles, out RolesNum);
                        if (_UserPermission >= RolesNum)
                        {
                            return true;
                        }
                    }
                    return false;
                }

                return true;
            }
        }
        #endregion

        #region Group Level

        public List<SelectListItem> GetGroupLevels(int selVale)
        {
            string[] arrayNameGroup = new string[] { "Guest", "Manager", "Admin", "Super Admin" };

            List<SelectListItem> lstItem = new List<SelectListItem>();
            int countItem = 1;
            foreach (var name in arrayNameGroup)
            {
                int currentPermission = Session["_UserPermission"] != null ? int.Parse(Session["_UserPermission"].ToString()) : 0;

                if (countItem < currentPermission)
                {
                    string value = countItem.ToString();
                    string text = name;
                    SelectListItem selItem = new SelectListItem();
                    selItem.Text = text;
                    selItem.Value = value;
                    if (countItem == selVale)
                    {
                        selItem.Selected = true;
                    }
                    lstItem.Add(selItem);
                }
                countItem++;
            }

            return lstItem;
        }

        #endregion


    }

    

}
